/******************************************************************************
* @file disk.c
* @author Zohar
* @version 1.00
* @date 2019.09.21
* @brief
******************************************************************************/
#include "disk.h"

#define DISK_PAGE_SIZE 256 //扇区大小,单位byte

//计划分配给fatfs 1M空间
#if 1
#define DISK_SECTOR_SIZE 512   //扇区大小，单位byte
#define DISK_SECTOR_COUNT 2048 //扇区个数 512*2048=1M
//块设为512byte，擦除单位还是4K，故此处写
#define DISK_ERASE_BLOCK_SIZE 8 //块大小，单位Kbyte,也可32K,一般不用32K
#else
#define DISK_SECTOR_SIZE 4096   //扇区大小，单位byte
#define DISK_SECTOR_COUNT 256   //扇区个数 256*4096=1M
//块设为4096byte，擦除单位还是4K，故此处写
#define DISK_ERASE_BLOCK_SIZE 1 //块大小，单位Kbyte,也可32K,一般不用32K
#endif

DRESULT spiFlash_disk_read(
    BYTE *buff,   /* Data buffer to store read data */
    LBA_t sector, /* Start sector in LBA */
    UINT count    /* Number of sectors to read */
)
{
    SPI_FLASH_BufferRead(buff,
                         sector * DISK_SECTOR_SIZE,
                         count * DISK_SECTOR_SIZE);

    return RES_OK;
}

DRESULT spiFlash_disk_write(
    BYTE *buff,   /* Data buffer to store read data */
    LBA_t sector, /* Start sector in LBA */
    UINT count    /* Number of sectors to read */
)
{
    if (sector % 8 == 0)
    {
        SPI_FLASH_SectorErase(sector * DISK_SECTOR_SIZE);
        // GetDataInSpiFlash(sector, 1);
    }
    debugline();
    SPI_FLASH_BufferWrite(buff,
                          sector * DISK_SECTOR_SIZE,
                          count * DISK_SECTOR_SIZE);
    GetDataInSpiFlash(sector, 1);

    return RES_OK;
}

DRESULT spiFlash_disk_ioctl(
    BYTE cmd,  /* Control code */
    void *buff /* Buffer to send/receive control data */
)
{
    switch (cmd)
    {
    case CTRL_SYNC:
        return RES_OK;

    /* 扇区数量 */
    case GET_SECTOR_COUNT:

        *(DWORD *)buff = DISK_SECTOR_COUNT; //1M 有2048个大小为512 bytes 的扇区
        return RES_OK;

        /* 扇区大小 */
    case GET_SECTOR_SIZE:
        //TODO尝试512
        *(WORD *)buff = DISK_SECTOR_SIZE; //spi flash的扇区大小是 4K Bytes,
        return RES_OK;

        /*块大小 */

    case GET_BLOCK_SIZE:
        *(DWORD *)buff = DISK_ERASE_BLOCK_SIZE;
        return RES_OK;

    default:
        return RES_PARERR;
    }

    return RES_OK;
}
